#!/user/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Sjy
Description: 是 dock 基类

'''

__all__ = ["Dock"]
import gui.components.qss as qss
import gui.controls.globalvar as GL
import gui.controls.settings as ST

from PyQt5 import QtCore, QtGui, QtWidgets

global DOCK_INSTANCES
DOCK_INSTANCES = {}

class CustomScrollArea(QtWidgets.QScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
    def eventFilter(self, obj, event):
        """事件过滤器"""
        if event.type() == QtCore.QEvent.Wheel:
            """禁用鼠标滚轮事件"""
            return True 
        return super().eventFilter(obj, event)
# class CustomTitleBar(QtWidgets.QFrame):
#     def __init__(self, *args, **kwargs):
#         self.setFixedHeight(40)
#         super(CustomTitleBar, self).__init__(*args, **kwargs)

#     def sizeHint(self):
#         size = QtWidgets.QFrame.sizeHint()
#         size.setHeight(24); 
#         super().sizeHint()
		

class Dock(QtWidgets.QDockWidget):
    def __init__(self, params:dict={}, parent=None):
        parent = parent or GL.get_value("py3d")
        super(Dock, self).__init__(parent)
        self.__desk = parent
        self.__params = params
        self.__ui = None
        self.init_config()
        
    def init_config(self) -> None:
        """初始化配置
        """
        objName = self.__params.get("objectName", "")
        DOCK_INSTANCES[objName] = self

        self.setObjectName(objName)
        title = self.__params.get("title", None)
        if title == None:
            self.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)  # 禁用所有特性，包括标题栏
            self.setTitleBarWidget(QtWidgets.QWidget())  # 设置一个空的 QWidget 作为标题栏
        else:
            self.setWindowTitle(title or "")
        self.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)

    def get_instance(self, name:str) -> QtWidgets.QDockWidget:
        """根据objectname 获取dock实例

        Args:
            name (str): objectname

        Returns:
            QtWidgets.QDockWidget: dock的实例
        """
        return DOCK_INSTANCES.get(name, None)

        # self.setFloating(False) # 一般默认不浮动
    def closeEvent(self, event) -> None:
        """重写关闭事件

        Args:
            event (_type_): qt关闭事件
        """
        super().closeEvent(event)
        name = self.__params.get("name", "")
        if name:
            self.__desk.closeChild(name)
    def showEvent(self, event) -> None:
        """重写显示事件

        Args:
            event (_type_): qt显示事件
        """
        super().showEvent(event)
        # 界面显示后初始化数据
        

    def add_to_desk(self, area:any=QtCore.Qt.LeftDockWidgetArea) -> None:
        """添加dock

        Args:
            area (any, optional): 位置. Defaults to QtCore.Qt.LeftDockWidgetArea.
                QtCore.Qt.LeftDockWidgetArea
                QtCore.Qt.RightDockWidgetArea
                QtCore.Qt.TopDockWidgetArea
                QtCore.Qt.BottomDockWidgetArea
        """
        self.__desk.addDockWidget(area, self)

    def _set_dock_ui(self, widget:QtWidgets.QWidget=None, objectName:str="frmDockContainer", align=QtCore.Qt.AlignmentFlag.AlignCenter) -> None:
        """设置 dock ui
        Args:
            widget (QtWidgets.QWidget, optional): 在dock内显示的ui. Defaults to None.
            objectName (str, optional): 对象名称. Defaults to None.
            margin (tuple, optional): 边距. Defaults to (3, 3, 3, 3).
            align (QtCore.Qt.AlignmentFlag, optional): 对齐方式. Defaults to QtCore.Qt.AlignmentFlag.AlignCenter.
        """
        scroll_area = CustomScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("QScrollArea{border:0px;}")
        dock_container = QtWidgets.QWidget()
        """
        为什么这样设置而不是通过 scroll_area 直接添加呢？ 
            是因为 scroll_area 如果设置layout的话，会使得内部组件自动缩放，而不是滚动条滚动，所以需要一个容器来放置widget，然后在这个容器中设置layout。
        """
        dock_container.setObjectName(objectName)
        layout = QtWidgets.QVBoxLayout()
        # lauout 主要用来设置容器内传入widget 的对齐方式
        # layout.setContentsMargins(*margin)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(widget)
        layout.setAlignment(align)
        dock_container.setLayout(layout)
        scroll_area.setWidget(dock_container)
        self.setWidget(scroll_area)
        self.raise_()
    def set_ui(self, widget:QtWidgets.QWidget=None, addToDock:bool=True) -> None:
        """设置ui

        Args:
            widget (QtWidgets.QWidget, optional): ui. Defaults to None.
        """
        self.__ui = widget
        addToDock and self._set_dock_ui(widget)
    def get_ui(self) -> QtWidgets.QWidget:
        """获取ui

        Returns:
            QtWidgets.QWidget: 返回ui
        """
        return self.__ui
    def on_load(self) -> None:
        """dock加载时的回调函数
        """
        pos = self.__params.get("pos", QtCore.Qt.LeftDockWidgetArea)
        self.add_to_desk(pos)
    
    def on_init(self) -> None:
        """dock初始化时的回调函数
        """
        pass
    def on_unload(self) -> None:
        """dock卸载时的回调函数
        """
        pass